#include <iostream>
#include <signal.h>
#include "Server.h"
#include <thread>
#include <condition_variable>
#include <mutex>
#include <signal.h>

#include "LogicSystem.h"
#include "AsioThreadPool.h"


//优雅退出方式选择宏
#define EXIT_METHOD_1 0





#if EXIT_METHOD_1
//服务器优雅的退出方法1
std::mutex mtx_;
std::condition_variable cond_;
bool b_stop_=false;
void SingalHandler(int signum)
{
    std::unique_lock<std::mutex> lock(mtx_);
    b_stop_=true;
    cond_.notify_one();
}




int main()
{
    auto pool = AsioThreadPool::GetInstance();
    try
    {
        
        boost::asio::io_context& io_context=pool->GetIOService();
        Server server(io_context, 8888);
        /**
         * 实现服务器优雅退出
         * 1. 收到SIGINT信号时，设置逻辑系统停止标志
         * 2. 逻辑系统处理完队列中的任务后，退出
         */
        signal(SIGINT,SingalHandler);
        signal(SIGTERM,SingalHandler);


        std::thread net_work_thread([&io_context,&server](){
            server.StartAccept();
            io_context.run();
        });
        std::unique_lock<std::mutex> lock(mtx_);
        cond_.wait(lock,[&](){return b_stop_;});


        LogicSystem::GetInstance()->stop();
        io_context.stop();
        net_work_thread.join();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
    
    return 0;
}

#else

int main()
{
    
    auto pool = AsioThreadPool::GetInstance();
    try
    {
        
        boost::asio::io_context io_context;
        Server server(pool->GetIOService(), 8888);
        server.StartAccept();
        /**
         * 实现服务器优雅退出2
         */
        //本质就是将信号作为一个事件注册给epoll模型或者IOCP模型，当信号到来时，会触发回调函数
        boost::asio::signal_set signals(io_context,SIGINT,SIGTERM);
        signals.async_wait([&](boost::system::error_code ec, int signum){
            LogicSystem::GetInstance()->stop();
            pool->Stop();
            io_context.stop();

        });
        
        io_context.run();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
    
    return 0;
}
#endif